package com.roger.cmdkit.cases;

import com.roger.cmdkit.base.CmdBase;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Random;

import javazoom.jl.player.Player;

public class DockVoice implements CmdBase {
    static SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    @Override
    public void cmdS(String[] args) {
        String path = System.getProperty("user.dir")+"\\mp3\\";
        File f = new File(path);
        if(f.exists()) {
            int max = f.list().length;
            if(max>0){
                try {
                    String name = f.list()[new Random().nextInt(max)];
                    String time = sdf.format(System.currentTimeMillis( ));
                    write(System.getProperty("user.dir")+"\\logs\\log.txt",time +": start play: " + name);
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(new File(path+name)));
                    Player player = new Player(new BufferedInputStream(bufferedInputStream));
                    player.play();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void write(String file, String content){
        try {
            String s = content +"\n";
            File f = new File(file);
            if(!f.getParentFile().exists()) f.getParentFile().mkdirs();
            if(!f.exists()) f.createNewFile();
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(f,true),"UTF-8");
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write(s);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
